import React, { Component } from 'react';
import { connect } from 'dva';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { FormattedMessage } from 'umi-plugin-react/locale';
import {
  Row,
  Col,
  Form,
  Button,
  Select,
  DatePicker,
  Statistic,
  Spin,
  Tooltip,
  Icon
} from 'antd';
import styles from './index.less';
import dataTime from '../../../utils/dataTime';
// 引入 ECharts 主模块
import echarts from 'echarts/lib/echarts';
// 引入折线图
import 'echarts/lib/chart/line';
// 引入提示框和标题组件
// 引入提示框和title组件
require("echarts/lib/component/tooltip");
require("echarts/lib/component/title");
// 引入legend模块
require("echarts/lib/component/legend");
// eslint-disable-next-line import/order
import moment from 'moment';
import { TimelineChart } from '@/components/Charts';
const { RangePicker } = DatePicker;
const dateFormat = 'YYYY/MM/DD';
const FormItem = Form.Item;
const Option = Select.Option;
let myChart;

@connect(({ accessTrends, loading }) => ({
  accessTrends,
  loading: loading.effects['accessTrends/fetch'],
}))

class AccessTrends extends Component {
  constructor() {
    super();
    this.state = {
      multipleTime: '1',
      login: false,
      listday: [{ day: '昨天' }, { day: '近7天' }, { day: '近30天' }],
      channel: '',
      from: '',
      to: '',
      range: '',
      timeB: false,
      number: '1'
    };
  }

  // eslint-disable-next-line react/sort-comp
  goDay = index => {
    // console.log('index', index); // 测试
    this.setState({
      // 切换css样式
      currentIndex: index,
    });
    const multipleTimeA = [
      { time: '' },
      { time: 'web' },
      { time: 'web' },
      { time: 'weixin' },
      { time: 'app' },
      { time: 'unknown' },
    ];
    const multipleTimeB = multipleTimeA[this.state.multipleTime];
    console.log(multipleTimeB);
    if (index === 0) {
      // 昨天图表渲染
      this.setState({
        timeB: true,
        number: '1'
      })
      let last1 = moment().subtract('days', 1).format('YYYY-MM-DD');
      this.timeFalseDate(multipleTimeB.time, '', last1, last1, 1);
    } else if (index === 1) {
      // 近7天图表
      this.setState({
        timeB: false,
        number: '1'
      })
      let last7 = moment().subtract('days', 7).format('YYYY-MM-DD');
      this.timeFalseDate(multipleTimeB.time, '', last7, '', 7);
    } else {
      // 近30天图表
      this.setState({
        timeB: false,
        number: '1'
      })
      let lart30 = moment().subtract('days', 30).format('YYYY-MM-DD');
      this.timeFalseDate(multipleTimeB.time, '', lart30, '', 30);

    }
  };

  // 图表数据
  timeFalseDate = (va, vb, vc, vd, ve) => {
    this.setState({
      login: true
    })
    let chartDataB = [];
    let xAxisData = []
    let seriesData1 = null
    let seriesData2 = null
    const { dispatch, currentUser } = this.props;

    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'accessTrends/fetch',
        payload: { channel: va, robotId: currentUser.robotId, from: vc, to: vd },
        callback: res => {
          console.log(res)

          if (res) {
            this.setState({
              login: false
            }, () => {
              if (res.xAxisData[0].length === 13) {
                let list = []
                res.xAxisData.map((item, index) => {
                  list.push(item.slice(11))
                })
                res.xAxisData = list
                this.lineEchart(res)
              } else {
                this.lineEchart(res)
              }
            })
          }
          xAxisData = res.xAxisData  // 日期
          seriesData1 = res.seriesData1 // 问答数
          seriesData2 = res.seriesData2// 访客数

          if (this.state.timeB) {
            for (let i = 0; i < 24; i++) {
              chartDataB.push({
                x: new Date(new Date().toLocaleDateString()).getTime() + 1000 * 60 * 60 * i,
                y1: seriesData1[i],
                y2: seriesData2[i],
              });
            }
          }
          if (this.state.timeB === false) {
            for (let i = 0; i < seriesData1.length; i++) {
              chartDataB.push({
                x: new Date(xAxisData[0]).getTime() + 1000 * 60 * 30 * 24 * 2 * i,
                y1: seriesData1[i],
                y2: seriesData2[i],
              });
            }
          }

          this.setState({
            chartDatB: chartDataB,
            askTotal: res.askTotal,
            visitorTotal: res.visitorTotal,
          });
          // console.log('componentWillMount', res);
        },
      });
    });
  };


  // 渲染页面前调用一次
  componentWillMount() {
    window.addEventListener("resize", function () {
      myChart.resize();
    });
    let sysTime = dataTime.formatDate(new Date().getTime()); // 初始时间
    let toTime = moment().subtract('days', 7).format('YYYY/MM/DD');
    this.setState({
      beginTime: toTime.replace(/\//g, '-'),
      overTime: sysTime.replace(/\//g, '-'),
    });
    let last7 = moment().subtract('days', 7).format('YYYY-MM-DD');
    this.timeFalseDate('', '', last7, '', 30);
   
  }

  lineEchart = res => {
    let seriesData2 = res.seriesData2
    let max
    // console.log(max)
    // 基于准备好的dom，初始化echarts实例
    myChart = echarts.init(document.getElementById('main'));
    // 绘制图表
    myChart.setOption(
      {
        color: ['#14c9c0 ', '#fb9505'],
        tooltip: {
          trigger: 'axis'
        },
        // toolbox: {
        //   left: 'center',
        //   // itemSize: 25,
        //   top: 45,
        //   feature: {
        //     dataZoom: {
        //       yAxisIndex: 'none'
        //     },
        //     saveAsImage: {}
        //   }
        // },
        legend: {
          data: ['问答次数（次）', '访问数量（人）'],
          icon: 'roundRect',
          itemWidth: 22,//图例图标宽度
          itemHeight: 10//图例图标高度
        },
        grid: {
          top: 100,
          left: '3%',
          right: '4%',
          bottom: '9%',
          containLabel: true
        },
       
        xAxis: [{
          type: 'category',
          axisLine: {
            lineStyle: {
              color: '#e0e0e0',
              width: 2,
            }
          },
          axisLabel: {
            show: true,
            textStyle: {
              color: '#808080',
            },
          },
          boundaryGap: false,
          offset:20, // x轴文字向下移动
          data: res.xAxisData,
        },
        ],

        yAxis: [
          {
            type: 'value',

            name: '问答次数（次）',
            nameTextStyle: {
              color: '#9a9a9a'
            },

            axisLabel: {
              formatter: '{value}',
              textStyle: {
                color: '#808080'
              }
            },
            splitLine: { //网格线
              show: false,
            },
            axisLine: {
              lineStyle: {
                color: '#14c9c0 ',
                width: 3,//这里是为了突出显示加上的  
              }
            }
          },
          {
            type: 'value',
            name: '访问数量（人）',
            nameTextStyle: {
              color: '#9a9a9a'
            },
            min: 0,
            max: max,
            axisLabel: {
              formatter: '{value}',
              textStyle: {
                color: '#808080',
              },
              show: true,
            },

            splitLine: { // 网格线
              show: true,
              lineStyle: {
                type: 'dashed'    //设置网格线类型 dotted：虚线   solid:实线
              },

            },
            axisLine: {
              lineStyle: {
                color: '#fb9505',
                width: 3,// 这里是为了突出显示加上的  
              }
            }
          }
        ],
        series: [
          {
            name: '问答次数（次）',
            type: 'line',
            data: res.seriesData1,
            smooth: true
          },
          {
            name: '访问数量（人）',
            type: 'line',
            data: res.seriesData2,
            yAxisIndex: 1,
            smooth: true
          }
        ]
      });
  }



  // 多选｛所有渠道1 网站2 微信3 app4 其它5｝
  handleChange = value => {
    this.setState({
      multipleTime: value,
    });
  };

  // 日期选择｛开始日期——结束日期｝
  onChange = (date, dateString) => {
    this.setState({
      beginTime: dateString[0].replace(/\//g, '-'),
      overTime: dateString[1].replace(/\//g, '-'),
    });
    if (dateString[0] === dateString[1]) {
      this.setState({
        timeB: true
      })
    } else {
      this.setState({
        timeB: false
      })
    }
    console.log(this.state.overTime);
  };

  // 查看 发送请求
  examineTime = () => {
    this.setState({
      // 切换css样式
      currentIndex: null,
    });
    const multipleTimeA = [
      { time: '' },
      { time: 'web' },
      { time: 'web' },
      { time: 'weixin' },
      { time: 'app' },
      { time: 'unknown' },
    ];
    const multipleTimeB = multipleTimeA[this.state.multipleTime];
    console.log(multipleTimeB);
    console.log(this.state.overTime);
    if (this.state.beginTime === this.state.overTime) {
      console.log('111')
      this.setState({
        timeB: true
      })
      this.timeFalseDate(multipleTimeB.time, '', this.state.beginTime, this.state.overTime, '');
    }
    if (this.state.beginTime !== this.state.overTime) {
      this.setState({
        timeB: false
      })
      this.timeFalseDate(multipleTimeB.time, '', this.state.beginTime, this.state.overTime, '');
    }
  };

  render() {
    const { number } = this.state
    let timeTickInterval = 60 * 60 * 1000 * 24 * 2
    let timeMask = 'YYYY-MM-DD'

    if (this.state.timeB) {
      timeTickInterval = 60 * 60 * 1000
      timeMask = 'HH:mm'
    }
    if (this.state.timeB === false) {
      timeTickInterval = 60 * 60 * 1000 * 24 * 2
      timeMask = 'YYYY-MM-DD'
    }

    return (
      <div className={styles.bac}>
        <PageHeaderWrapper>
          <div className={styles.backgroundp}>
            <Row className={styles.colorBackground}>
              <Col style={{ paddingLeft: 20, paddingTop: 6 }} xs={24} span={3} sm={24} md={24} lg={4} xl={3}>
                <div className={styles.buttonAB}>
                  <span style={{ fontSize: 16, borderLeft: "5px solid #13c2f3", paddingLeft: 10,color: '#4B5475', fontWeight: 600}}>
                    <FormattedMessage
                      id="app.accessTrends.Access-trend"
                      defaultMessage="Access trend"
                    />
                  </span>
                  <span style={{ marginLeft: 12 }}>
                    <Tooltip
                      placement="top"
                      title='即某个时间段内访客数量和问答次数的曲线图，可切换时间和问答渠道查看'
                      arrowPointAtCenter
                    >
                      <Icon type="info-circle" />
                    </Tooltip>
                  </span>
                </div>
              </Col>
              <Col span={9} xs={0} sm={0} md={0} lg={0} xl={5} />
              <Col span={12} xs={24} sm={24} md={24} lg={20} xl={16} className={styles.zsy}>
                <Form layout="inline" className={styles.buttonA}>
                  {this.state.listday.map((item, index) => {
                    return (
                      <FormItem key={index}>
                        <span
                          className={styles.cursorA}
                          style={{ color: index === this.state.currentIndex ? 'rgb(19, 194, 243)' : '' }}
                          onClick={() => this.goDay(index)}
                        >
                          {item.day}
                        </span>
                      </FormItem>
                    );
                  })}
                  <FormItem>
                    <Select
                      defaultValue={number}
                      style={{ width: 120 }}
                      onChange={this.handleChange}
                    >
                      <Option value="1">
                        <FormattedMessage
                          id="app.accessTrends.all-channels" defaultMessage="All channels" />
                      </Option>
                      <Option value="2">
                        <FormattedMessage id="app.accessTrends.website" defaultMessage="Website" />
                      </Option>
                      <Option value="3">
                        <FormattedMessage id="app.accessTrends.weixin" defaultMessage="weixin" />
                      </Option>
                      <Option value="4">
                        <FormattedMessage id="app.accessTrends.app" defaultMessage="app" />
                      </Option>
                      <Option value="5">
                        <FormattedMessage id="app.accessTrends.other" defaultMessage="other" />
                      </Option>
                    </Select>
                  </FormItem>
                  <FormItem>
                    <RangePicker
                      onChange={this.onChange}
                      style={{ width: 220 }}
                      defaultValue={[
                        moment(this.state.beginTime, dateFormat),
                        moment(this.state.overTime, dateFormat),
                      ]}
                      format={dateFormat}
                    />
                  </FormItem>
                  <FormItem className='buttonYs'>
                    <Button onClick={this.examineTime} icon="check">
                      {<FormattedMessage id="app.accessTrends.examine" defaultMessage="Examine" />}
                    </Button>
                  </FormItem>
                </Form>
              </Col>
            </Row>
            {/* 表头开始 */}
            <Row style={{ paddingLeft: 10, height: 75 }} className={styles.colorBackgrounds}>
              <Col span={24}>
                <div className={styles.textHeader}>
                  <div className={styles.textHeaderA}>
                    <div className={styles.textHeader1}>
                      {
                        <FormattedMessage
                          id="app.accessTrends.access-number"
                          defaultMessage="The Proportion of Sales"
                        />
                      }
                    </div>
                    <div className={styles.textHeader2}>
                      {/* {this.state.visitorTotal} */}
                      <Statistic valueStyle={{fontSize:30,color:'#333'}} suffix={<FormattedMessage id="app.accessTrends.person" defaultMessage="accessTrends Person" />} value={this.state.visitorTotal} />
                    </div>
                  </div>
                  <div className={styles.textHeaderB} style={{ marginLeft: 20 }}>
                    <div className={styles.textHeader1}>
                      {
                        <FormattedMessage
                          id="app.accessTrends.number-questions-answers"
                          defaultMessage="Number of questions"
                        />
                      }
                    </div>
                    <div className={styles.textHeader2}>
                      {/* {this.state.askTotal} */}
                  <Statistic valueStyle={{fontSize:30,color:'#333'}} suffix={<FormattedMessage id="app.accessTrends.next" defaultMessage="next" />} value={this.state.askTotal} />
                    </div>
                  </div>
                </div>
              </Col>
            </Row>
            {/* 图表开始 */}

            <Row id="main" className={styles.colorBackgrounds}>
              <Spin spinning={this.state.login}>
                <Col span={24}>
                  <div style={{ margin: '0px 30px 0px 30px' }}>

                  </div>
                </Col>
              </Spin>
            </Row>
          </div>
        </PageHeaderWrapper>
      </div>
    );
  }
}


export default connect(({ user }) => ({
  currentUser: user.currentUser,
}))(AccessTrends);

